package com.ukefu.webim.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.webim.WebIMClient;
import com.ukefu.webim.service.repository.ConsultInviteRepository;
import com.ukefu.webim.web.model.CousultInvite;

public class WebSseEmitterClient{
	
	private HashMap<String, WebIMClient> imClientsMap = new HashMap<String, WebIMClient>();
	
	public List<WebIMClient> getClients(String userid){
		Collection<WebIMClient> values = imClientsMap.values() ;
		List<WebIMClient> clents = new ArrayList<WebIMClient>();
		for(WebIMClient client : values){
			if(client.getUserid().equals(userid)){
				clents.add(client) ;
			}
		}
		return clents;
	}
	
	public int size(){
		return imClientsMap.size() ;
	}
	
	public void clean(){
		List<WebIMClient> clients = new ArrayList<WebIMClient>();
		Collection<WebIMClient> values = imClientsMap.values() ;
		for(WebIMClient client : values) {
			CousultInvite invite = OnlineUserUtils.cousult(client.getAppid(), client.getOrgi(), UKDataContext.getContext().getBean(ConsultInviteRepository.class));
			if(clients.size() < 5000 && (System.currentTimeMillis() - client.getTime()) > (invite.getTimeout() * 2 * 1000)) {
				clients.add(client);
			}
		}
		if(clients.size() > 0) {
			for(WebIMClient client:clients) {
				this.removeClient( client.getUnikey(),client.getUserid(),client.getClient() , client.getOrgi(), true);
			}
		}
	}
	
	public void putClient(String userid , WebIMClient client){
		imClientsMap.put(client.getClient(), client) ;
	}
	
	public void updateClient(String sessionid,String userid , String client) throws Exception{
		List<WebIMClient> keyClients = this.getClients(userid) ;
		for(int i=0 ; i<keyClients.size() ; i++){
			WebIMClient webIMClient = keyClients.get(i) ;
			if(webIMClient.getClient()!=null && webIMClient.getClient().equals(client)){
				webIMClient.setTime(System.currentTimeMillis());
				break ;
			}
		}
	}
	
	public void removeClient(String unikey,String userid , String client ,String orgi, boolean timeout) {
		List<WebIMClient> keyClients = this.getClients(userid) ;
		for(int i=0 ; i<keyClients.size() ; i++){
			WebIMClient webIMClient = keyClients.get(i) ;
			if(webIMClient.getClient()!=null && webIMClient.getClient().equals(client)){
				imClientsMap.remove(client) ;
				keyClients.remove(i) ;
				break ;
			}
		}
		if(keyClients.size() == 0 && timeout == true){
			try {
				OnlineUserUtils.offline(unikey , userid, orgi);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
